import Http from '../../../utils/http.js';
var WxParse = require('../../../utils/wxParse/wxParse.js');
import { isEmpty } from '../../../utils/util.js';
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    commodityCode: '100081',//当前商品code
    current: 0, // 索引值
    loading: false,
    commodityMaterial: {},
    commodityCommon: {},
    activeTab: 'detail',
    evalutionLoading: false,//评论加载
    evalutionLoadingComplete: false,//评论数据加载完毕
    evalutionPage: 1,//评论当前分页
    evalutionList: [],
    product:'',//实物种类
    specifications:[],//种类分组
    finnalPriceShow:false,//显示最终价格
    finnalPrice:0,//选完规格后最终的商品价格
    isBuyNow:false,
    commodityCount:1,//数量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      commodityCode: options.commodityCode || '100081'
    })
    this.getCommodityDetail(); 
    this.getCommentList();
  },
  //获取评论数据
  getCommentList() {
    Http.Request('GET', `/api/customer/commodity/getCommodityCommentByCode/${this.data.commodityCode}/v1?page=${this.data.evalutionPage}&size=${app.globalData.pageSize}`).then(res => {
      //返回数组为空或者返回的条数小于设定的size认为所有数据已经加载完成
      if (res && (!res.length || res.length < app.globalData.pageSize)) {
        this.setData({
          evalutionLoadingComplete: true
        })
      }
      this.setData({
        evalutionList: this.data.evalutionList.concat(res),
        evalutionLoading: false
      })
    }).catch(err => {

    })
  },
  getCommodityDetail() {
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    Http.Request('GET', `/api/customer/commodity/getCommodityByCode/${this.data.commodityCode}/v1`).then(res => {
      this.setData({
        commodityCommon: res.commodityCommon,
        commodityMaterial: res.commodityMaterial,
        product: res.product||'',
        specifications: res.specifications||[],
        loading: false
      })
      WxParse.wxParse('commodityDetail', 'html', this.data.commodityCommon.commodityDetail || app.globalData.defaultHtml, this, 25);
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      app.globalFn.reLoad(this.getCommodityDetail, err)
    })
  },
  swiperChange(e) {
    const current = e.detail.current;
    this.setData({
      current
    })
  },
  //切换详情、评价
  tabSwitch(e) {
    const activeTab = e.currentTarget.dataset.type;
    this.setData({
      activeTab
    })
  },
  //数量增加
  updateCount(e){
    this.setData({
      commodityCount:e.detail
    })
  },
  //滑动到底部
  scrollLower() {
    console.log('到底')
    if (this.data.evalutionLoading || this.data.evalutionLoadingComplete) return;
    this.setData({
      evalutionLoading: true,
      evalutionPage: this.data.evalutionPage + 1
    })
    this.getCommentList()

  },
  //立即购买/加入购物车
  handleBtnClick(e){
    const type = e.currentTarget.dataset.type;
    this.selectComponent("#maskModals").showChoose();
    this.setData({
      isBuyNow: type ==='buyNow'
    })
  },
  //选择规格
  valueClick(e){
    const speIndex = e.currentTarget.dataset.speindex;
    const valueIndex = e.currentTarget.dataset.index;
    let specifications = this.data.specifications
    specifications[speIndex].specValues.forEach(o=>{
      o.selected = false
    });
    specifications[speIndex].specValues[valueIndex].selected = true;
    this.setData({
      specifications
    })
    let selectAll = false;
    for (let i = 0; i < specifications.length;i++){
      selectAll = specifications[i].specValues.some(s => {
        return s.selected === true
      })
      if (!selectAll)break;
    }
    //所有的规格都选择了之后，判断产品价格
    if (selectAll){
      let product = this.data.product;
      specifications.forEach((o,index)=>{
        const columnName = o.specValues.find(s=>{
          return s.selected === true
        }).specValue;
        console.log(columnName)
        product = product.filter(p=>{
          return p[`column${index}`] === columnName
        })
      })
      this.setData({
        finnalPriceShow:true,
        finnalPrice: product[0].price,
        bizid: product[0].bizid
      })
    }else{
      this.setData({
        finnalPriceShow:false
      })
    }

  },
  //选好了
  handleSelectOk(){
    if (!this.data.finnalPriceShow && !isEmpty(this.data.specifications))return;
    //立即购买
    if (this.data.isBuyNow){
      const specifications = this.data.specifications;
      let labels = '';
      specifications.forEach(o=>{
        if (o.specValues && o.specValues.length){
          const label = o.specValues.find(s=>{
            return s.selected===true
          }).specValue;
          labels += label+' ';
        }
      })
      const commodityList = [{
        commodityCode: this.data.commodityCode,
        firstImage: this.data.commodityCommon.commodityImage[0],
        product: labels,
        count: this.data.commodityCount,
        productBizid: this.data.bizid,
        commodityName: this.data.commodityCommon.commodityGroupName,
        commodityPrice:this.data.finnalPrice
      }] 
      wx.navigateTo({
        url: `./createOrder/index?commodityList=${JSON.stringify(commodityList)}`
      })
    }else{//加入购物车
      const data = {
        commodityCode: this.data.commodityCode,
        count: this.data.commodityCount,
        productBizid: this.data.bizid
      }
      Http.Request('POST', `/api/customer/shoppingCart/add/v1`,data).then(res=>{
        wx.showToast({
          title: '加入购物车成功',
          icon: "success",
          duration: app.globalData.duration
        })
        this.selectComponent("#maskModals").hideModal();
      }).catch(err=>{
        wx.showToast({
          title: err,
          icon: "none",
          duration: app.globalData.duration
        })
        this.selectComponent("#maskModals").hideModal();
      })
    }
  }
})